import { ref, reactive, watch } from "vue";

//有分页的数据
interface PaginationData<T> {
  data: T;
  total: number;
}
type ReturnPromiseType<T> = T extends (
  ...args: any[]
) => Promise<PaginationData<infer U>>
  ? U
  : never;

interface useQueryListOptions {
  watchPage?: boolean; //分页条件改变是否自动请求
}
const useQueryList = <T extends (...args: any) => any>(
  apiFn: T,
  options?: useQueryListOptions
) => {
  const list = ref<ReturnPromiseType<T>>();
  const total = ref(0);
  const errorMsg = ref();
  const loading = ref(false);
  const pagination = reactive({
    page: 1,
    psize: 10,
  });
  const getList = async (args?: any) => {
    loading.value = true;
    try {
      const res = await apiFn(pagination);
      list.value = res.data;
      total.value = res.total;
    } catch (error) {
      //错误处理
      console.log(error);
      errorMsg.value = error;
    } finally {
      loading.value = false;
    }
  };
  getList();
  if (options?.watchPage) {
    watch(pagination, async () => await getList(), { deep: true });
  }
  return {
    list,
    pagination,
    total,
    loading,
    errorMsg,
    getList,
  };
};
export default useQueryList;
